import { login, getInfo, getUserDetailById } from '@/api/user'
import { setToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    userToken: null,
    userInfo: {},
    timeStamp: 0
  },
  mutations: {
    setToken(state, payload) {
      state.userToken = payload
      state.timeStamp = Date.now()
      setToken(payload)
    },
    setUserInfo(state, payload) {
      state.userInfo = payload
    }
  },
  actions: {
    async loginAction({ commit }, payload) {
      const data = await login(payload)
      console.log(data)
      commit('setToken', data)
    },
    async getInfo({ commit }) {
      const res = await getInfo()
      const detail = await getUserDetailById(res.userId)
      const userInfo = { ...res, ...detail }
      commit('setUserInfo', userInfo)
      return res
    },
    logout({ commit }) {
      commit('setToken', null)
      commit('setUserInfo', {})
      commit('permission/setRoutes', [], { root: true })
    }
  }
}
